{include file="common/head"}
<div style="padding: 16px;">
  <table class="layui-hide" id="test" lay-filter="test"></table>
</div>
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm layui-bg-blue" lay-event="add">添加分类</button>
  </div>
</script>
<script type="text/html" id="barDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs layui-bg-orange" lay-event="update">编辑</a>
    <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="del">删除</a>
    <!-- <a class="layui-btn layui-btn-xs layui-bg-gray" lay-event="read">查看文章</a> -->
    <!-- <a class="layui-btn layui-btn-xs layui-bg-gray" lay-event="userInfo">查看发言者</a> -->

  </div>
</script>
{include file="common/bottom"}
<script type="text/html" id="addCate">
  <div class="layui-form layui-form-pane"  lay-filter="add" style="margin: 16px;">
      <div class="add-container addImg">
                      <div class="layui-form-item">
          <label class="layui-form-label">分类图片</label>
          <div class="layui-input-block">
               <div>
                  <button type="button" class="layui-btn" id="ID-upload-demo-btn">
                      <i class="layui-icon layui-icon-upload"></i> 上传
                  </button>
              </div>
              <div style="width: 132px;">
                  <div class="layui-upload-list">
                      <img class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;">
                      <div id="ID-upload-demo-text"></div>
                  </div>
                  <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
                      <div class="layui-progress-bar" lay-percent=""></div>
                  </div>
              </div>
             
          </div>
      </div>
          <div class="layui-form-item">
                  <label class="layui-form-label">分类</label>
                  <div class="layui-input-block">
                  <select name="pid">
                      <option value="-1" disabled>请选择</option>
                      <option value="0">添加父级分类</option>
                      {volist name="list" id="cate"}
                      <option value="{$cate.id}" class="layui-font-blue">{$cate.category}</option>
                          {if $cate.child neq null}
                              {volist name="cate.child" id="two"}
                              <option value="{$two.id}">| --- {$two.category}</option>
                              {/volist}
                          {/if}
                      {/volist}
                  </select>
                  </div>
              </div>  
              <div class="layui-form-item">
                      <label class="layui-form-label">分类名称</label>
                      <div class="layui-input-block">
                      <input type="text" name="category" lay-verify="required" placeholder="请输入分类名称" autocomplete="off" class="layui-input">
                      </div>
                  </div>
                  <div class="layui-form-item sort">
                      <label class="layui-form-label">权重</label>
                      <div class="layui-input-inline" style="width: 100px;">
                          <input type="number" name="sort" placeholder="" autocomplete="off" value="0" class="layui-input" min="0" step="1" lay-affix="number">
                      </div>
                  </div>
                      <div class="layui-form-item">
                          <label class="layui-form-label">是否显示</label>
                          <div class="layui-input-block">
                          <input type="checkbox" name="is_show" checked lay-skin="switch" lay-filter="switchTest" title="ON|OFF">
                          </div>
                      </div>          
              <div class="layui-form-item">
                  <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="add" id="clickBtn">添加分类</button>
              </div>
              </div>
          </div>
</script>
<script type="text/html" id="status">
    <input type="checkbox" name="status" value="{{= d.id }}" title="显示|" lay-skin="switch" lay-filter="status" {{= d.status == 1 ? "checked" : "" }}>
  </script>
<script>
  layui.use(['table', 'dropdown'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    const upload = layui.upload;
    const form = layui.form
    const element = layui.element;
    var $ = layui.$
    // 创建渲染实例
    table.render({
      elem: '#test',
      url: '/admin/category/list',
      toolbar: '#toolbarDemo',
      parseData: function (res) {
        return {
          "code": res.code, // 解析接口状态
          "msg": res.msg, // 解析提示文本
          "count": res.count, // 解析数据长度
          "data": res.data
        };
      },
      defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
        title: '提示',
        layEvent: 'LAYTABLE_TIPS',
        icon: 'layui-icon-tips',
        onClick: function (obj) { // 2.9.12+
          layer.alert('自定义工具栏图标按钮');
        }
      }],
      height: 'full',
      css: [
        '.layui-table-tool-temp{padding-right: 145px;}'
      ].join(''),
      cellMinWidth: 80,
      totalRow: true, // 开启合计行
      page: true,
      cols: [[
        {
          field: 'category', width: 150, title: '分类名称', templet: function (d) {
            str = '-'
            return d.level != 1 ? str.repeat(d.level * 2) + d.category : `<span class="layui-font-black">${d.category}</span>`
          }
        },
        {
          field: 'img_path', width: 150, title: '分类图片', templet: function (d) {
            if(d.level == 2){
               return ` <img style="width: 30px;height: 30px;" src="${d.img_path}" alt="">`
            }else{
              return `<span class="layui-font-black">父级分类</span>`
            }
          }
        },
        {
          field: 'is_show', width: 80, title: '展示', templet: function (d) {
            if (d.is_show == 1) {
              return '<span class="layui-badge layui-bg-blue">显示</span>'
            } else {
              return '<span class="layui-badge layui-bg-black">隐藏</span>'
            }
          }
        },
        { field: 'sort', width: 80, title: '权重', sort: true, edit: 'number', },
        { field: 'create_time', title: '创建时间', width: 200 },
        { title: '操作', width: 300, minWidth: 125, toolbar: '#barDemo' }
      ]],
      done: function () {
        var id = this.id;
        // 删除选中
       
      },
      error: function (res, msg) {
        console.log(res, msg)
      }
    });
    function templet(type = 'add', id = '') {
            const ope = layer.open({
                type: 1
                , title: '分类'
                , area: '350px',
                resize: false,
                shadeClose: true,
                content:$('#addCate').html(),
                success: function () {
                    let img_path = ''
                    var uploadInst = upload.render({
                        elem: '#ID-upload-demo-btn',
                        url: '/admin/category/uploadImg',
                        field: 'img',
                        before: function (obj) {
                            // 预读本地文件示例，不支持ie8
                            obj.preview(function (index, file, result) {
                                $('#ID-upload-demo-img').attr('src', result); // 图片链接（base64）
                            });
                            element.progress('filter-demo', '0%'); // 进度条复位
                            layer.msg('上传中', { icon: 16, time: 0 });
                        }, done: function (res) {
                            // 若上传失败
                            if (res.errno > 0) {
                                return layer.msg('上传失败');
                            } else {
                                img_path = res.data.url
                            }
                            $('#ID-upload-demo-text').html(''); // 置空上传失败的状态
                        },
                        error: function () {
                            // 演示失败状态，并实现重传
                            var demoText = $('#ID-upload-demo-text');
                            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                            demoText.find('.demo-reload').on('click', function () {
                                uploadInst.upload();
                            });
                        },
                        // 进度条
                        progress: function (n, elem, e) {
                            element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
                            if (n == 100) {
                                layer.msg('上传完毕', { icon: 1 });
                            }
                        }
                    })
                    let url = ''
                    if (type == 'update') {
                        $('#clickBtn')[0].innerText = '更新分类'
                        url = '/admin/category/update/id/' + id
                        $.ajax({
                            url: '/admin/category/getData/id/' + id
                            , dataType: 'json'
                            , success: (res) => {
                                let data = res.data
                                form.val('add', {
                                    'pid': data.pid
                                    , 'category': data.category
                                    , 'sort': data.sort
                                    , 'is_show': data.is_show
                                })
                                $('#ID-upload-demo-img').attr('src', data.img_path)
                                img_path = data.img_path
                            }
                        })
                    } else {
                        url = '/admin/category/add'
                    }
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(add)', function (data) {
                        var field = data.field; // 获取表单字段值
                        field['img_path'] = img_path
                        field['is_show'] = field.is_show == 'on' ? '1' : 0
                        // field['img_path'] = img_path
                        $.ajax({
                            url: url
                            , type: 'post'
                            , dataType: 'json'
                            , data: field
                            , success: (res) => {
                                if (res.code) {
                                    layer.msg('操作成功')
                                    // window.location.reload()
                                } else {
                                    layer.msg(res.message, { icon: 5 })
                                }
                            }
                        })
                        layer.close(ope)
                        return false; // 阻止默认 form 跳转
                    });
                }
            });
        }
    // 工具栏事件
    table.on('toolbar(test)', function (obj) {
      var id = obj.config.id;
      var checkStatus = table.checkStatus(id);
      var othis = lay(this);
      switch (obj.event) {
        case 'add':
          templet('add')
          break
      };
    });
    // 表头自定义元素工具事件 --- 2.8.8+
    table.on('colTool(test)', function (obj) {
      var event = obj.event;
      if (event === 'email-tips') {
        layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
          title: '当前列属性配置项'
        });
      }
    });

    table.on('tool(test)', function (obj) { // 双击 toolDouble
      var data = obj.data; // 获得当前行数据
      if (obj.event === 'del') {
        delCom(data.id)
      } else if (obj.event == 'read') {
        layer.open({
          title: data.content,
          type: 2,
          area: ['80%', '80%'],
          content: '/index/article/index.html?art_id=' + data.article_id
        });
      } 
      else if (obj.event == 'update') {
        templet('update',data.id)
      }
    });
    // 复选框 批量删除
    table.on('checkbox(test)', function (obj) {
      if (obj.checked) {
        delObj.push(obj)
      } else {
        delObj.pop(obj)
      }
    });
    // 行单击事件
    table.on('row(test)', function (obj) {
      //layer.closeAll('tips');
    });
    // 行双击事件
    table.on('rowDouble(test)', function (obj) {
    });

    // 单元格编辑事件
    table.on('edit(test)', function (obj) {
      var field = obj.field; // 得到字段
      var value = obj.value; // 得到修改后的值
      var data = obj.data; // 得到所在行所有键值
      // 值的校验
      if (field == 'sort') {
        var regPos = /^[0-9]+.?[0-9]*/
        if (!regPos.test(obj.value)) {
          layer.tips('输入的排序格式应为数字', this, { tips: 1 });
          return obj.reedit();
        } else {
          $.ajax({
            url: '/admin/article/doUpdate'
            , type: 'post'
            , data: {
              id: data.id
              , sort: obj.value
            }
            , dataType: 'json'
            , success: (res) => {
              /*  if (res.code == 200) {
                 layer.msg('修改成功', { icon: 6 })
               } else {
                 layer.msg('删除失败', { icon: 5 })
               }
*/
            }
          })
          table.reload('test', {
            where: {
            }
          })
        }
      }

      layer.msg('编辑成功', { icon: 1 });

      // 其他更新操作
      var update = {};
      update[field] = value;
      obj.update(update);
    });
  });
</script>
</body>

</html>